package com.lingyun.mqttserver.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingyun.mqttserver.dao.mapper.*;
import com.lingyun.mqttserver.dao.pojo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lingyun.mqttserver.service.ModbusCommandService;
import com.lingyun.mqttserver.util.JSONUtil;
import com.serotonin.modbus4j.msg.ModbusRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ModbusCommandServiceImpl implements ModbusCommandService {

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private LowerComputerVariableMapper variableMapper;

    @Autowired
    private MqttMessageService mqttMessageService;
    @Autowired
    private DeviceGroupMappingMapper deviceGroupMappingMapper;
    @Autowired
    private DeviceTypeMapper deviceTypeMapper;
    @Autowired
    private LowerComputerVariableMapper lowerComputerVariableMapper;
    @Autowired
    private MqttScreenVariableMappingVariableMapper mqttScreenVariableMappingVariableMapper;
    @Autowired
    private MqttScreenVariableMappingMapper mqttScreenVariableMappingMapper;


    @Override
    public int sendSettingUpdateClient(Integer deviceId, String port) {
        try {
            // 获取设备
            DeviceInfo deviceInfo = deviceInfoMapper.selectById(deviceId);

            // 获取modbus列表
            List<String> settingCommand = generateModbusCommands(deviceId, port);
            String modbusList = settingCommand.toString();
            HashMap<String, Object> sendMqtt = new HashMap<>();
            sendMqtt.put("port", port);
            sendMqtt.put("clientModbus", modbusList);
            // 转为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String sendMqttJson = objectMapper.writeValueAsString(sendMqtt);
            // 设置topic与指令
            mqttMessageService.sendDeviceCommand(deviceInfo.getHardwareAddress(), sendMqttJson);
            return 1;
        } catch (Exception e) {
            log.error(e.getMessage() + "发送mqtt-Modbus列表报错");
            return 0;
        }

    }

    @Override
    public int sendSettingUpdateServer(Integer deviceId, String port) {

        try{
            // 获取分组下所有下位机
            List<DeviceInfo> groupDevices = getGroupDevices(deviceId);

            // 获取该设备
            DeviceInfo deviceInfoAddress = deviceInfoMapper.selectById(deviceId);

            // 屏幕指令集
            ArrayList<String> modbusScreen = new ArrayList<>();
            groupDevices.forEach(deviceInfo -> {
                List<String> modbusList1 = generateModbusCommands(deviceInfo.getId(), "1");
                List<String> modbusList2 = generateModbusCommands(deviceInfo.getId(), "2");
                if (!modbusList1.isEmpty()){
                    modbusScreen.addAll(modbusList1);
                }
                if (!modbusList2.isEmpty()){
                    modbusScreen.addAll(modbusList2);
                }
            });

            // 转为字符串
            String modbusScreenString = modbusScreen.toString();
            HashMap<String, Object> modbusMap = new HashMap<>();
            modbusMap.put("time", "300");
            modbusMap.put("modbusScreen", modbusScreenString);

            // 转为JSON格式
            String sendMqttJson = new ObjectMapper().writeValueAsString(modbusMap);
            // 设置topic与指令
            mqttMessageService.sendDeviceCommand(deviceInfoAddress.getHardwareAddress(), sendMqttJson);
            return 1;
        } catch (Exception e) {
            log.error(e.getMessage() + "写入屏幕MQTT失败");
        }
        return 0;
    }

    @Override
    public int sendGetLowerComputer(Integer deviceId, String modbus, String hardwareAddressId) {

        try{
            // 解析modbus
            ModbusRequest modbusRequest = parseModbusRequest(modbus);

            // 获取分组下所有下位机
            List<DeviceInfo> groupDevices = getGroupDevices(deviceId);

            if (groupDevices.isEmpty()){
                log.error("没有找到硬件设备:" + hardwareAddressId + "\n指令为：" + modbus);
                return 0;
            }

            // 所有的id
            List<Integer> groupDeviceIds = groupDevices.stream().map(DeviceInfo::getId).toList();

            // 有该从站地址的设备
            List<Integer> list = lowerComputerVariableMapper.selectObjs(new QueryWrapper<LowerComputerVariable>().select("DISTINCT device_id").in("device_id", groupDeviceIds).eq("slave_address", modbusRequest.slaveAddress));

            if (list.size() < 0){
                log.error("没有找到硬件设备:" + hardwareAddressId + "\n指令为：" + modbus);
                return 0;
            }

            Integer lowerComputerDeviceId = list.get(0);

            // 从数据库调用值回复
            String modbusResponse = processModbusRequest(lowerComputerDeviceId, modbus);

            // 设置发送指令
            HashMap<String, Object> map = new HashMap<>();
            map.put("modbus", modbusResponse);
            String command = JSONUtil.toJSON(map);

            // 发送
            mqttMessageService.sendDeviceCommand(hardwareAddressId, command);
            return 1;
        } catch (Exception e){
            log.error(e.getMessage() + "发送下位机获取指令错误");
            return 0;
        }
    }

    @Override
    public int sendSetLowerComputer(Integer deviceId, String modbus) {
        // 解析modbus
        ModbusRequest modbusRequest = parseModbusRequest(modbus);


        // 获取分组下所有下位机
        List<DeviceInfo> groupDevices = getGroupDevices(deviceId);
        if (groupDevices.isEmpty()){
            return 0;
        }

        // 所有的id
        List<Integer> groupDeviceIds = groupDevices.stream().map(DeviceInfo::getId).toList();

        // 有该从站地址的设备
        List<Integer> list = lowerComputerVariableMapper.selectObjs(new QueryWrapper<LowerComputerVariable>().select("DISTINCT device_id").in("device_id", groupDeviceIds).eq("slave_address", modbusRequest.slaveAddress));

        if (list.isEmpty()){
            return 0;
        }

        // 转换为json格式
        HashMap<String, Object> map = new HashMap<>();
        map.put("modbus", modbus);
        String command = JSONUtil.toJSON(map);

        // 循环发送
        list.forEach(integer -> {
            DeviceInfo deviceInfo = deviceInfoMapper.selectById(integer);
            mqttMessageService.sendDeviceCommand(deviceInfo.getHardwareAddress(), command);
        });


        return 0;
    }


    /**
     * 获取该设备下的分组的所有下位机设备
     * @param deviceId
     * @return
     */
    private List<DeviceInfo> getGroupDevices(Integer deviceId) {
        // 1. 通过设备ID查询设备分组映射
        DeviceGroupMapping mapping = deviceGroupMappingMapper.selectOne(
                new QueryWrapper<DeviceGroupMapping>()
                        .eq("device_id", deviceId)
        );

        if (mapping == null) {
            return new ArrayList<>();
        }

        // 2. 通过分组ID查询该分组下的所有设备
        List<DeviceGroupMapping> deviceGroupMappings = deviceGroupMappingMapper.selectList(
                new QueryWrapper<DeviceGroupMapping>()
                        .eq("group_id", mapping.getGroupId())
        );

        // 获取分组下的设备
        ArrayList<DeviceInfo> groupDevices = new ArrayList<>();
        deviceGroupMappings.forEach(deviceGroupMapping -> {
            DeviceInfo deviceInfo = deviceInfoMapper.selectById(deviceGroupMapping.getDeviceId());
            groupDevices.add(deviceInfo);
        });

        // 3. 过滤出下位机类型的设备
        return groupDevices.stream()
                .filter(device -> {
                    // 通过设备类型ID查询设备类型
                    DeviceType deviceType = deviceTypeMapper.selectById(device.getDeviceType());
                    return deviceType != null && "lower_computer".equals(deviceType.getDeviceType());
                })
                .collect(Collectors.toList());
    }

    /**
     * 为指定设备生成Modbus读取指令字符串列表
     */
    public List<String> generateModbusCommands(Integer deviceId, String port) {

        if (deviceId == null) {
            log.error("设备ID必须为正整数");
            return new ArrayList<>();
        }

        List<String> commands = new ArrayList<>();

        // 1. 验证设备存在
        DeviceInfo device = deviceInfoMapper.selectById(deviceId);
        if (device == null) {
            log.error("设备不存在" + deviceId + " 端口：" + port);
            return new ArrayList<>();
        }

        // 2. 获取设备的所有变量
        QueryWrapper<LowerComputerVariable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId);
        queryWrapper.eq("port", port);
        List<LowerComputerVariable> variables = variableMapper.selectList(queryWrapper);

        if (variables.isEmpty()) {
            log.error("设备没有配置变量" + deviceId + " 端口：" + port);
            return new ArrayList<>();
        }

        // 3. 按从站地址、寄存器类型分组变量
        Map<String, List<LowerComputerVariable>> groupedVariables = groupVariables(variables);

        // 4. 为每个分组生成连续的读取区间
        for (Map.Entry<String, List<LowerComputerVariable>> entry : groupedVariables.entrySet()) {
            List<AddressRange> ranges = mergeContinuousAddresses(entry.getValue());

            // 5. 为每个区间生成Modbus指令字符串
            for (AddressRange range : ranges) {
                String command = generateModbusCommandString(range);
                if (command != null) {
                    commands.add(command);
                }
            }
        }

        return commands;
    }


    /**
     * 处理Modbus请求并生成响应
     */
    public String processModbusRequest(Integer deviceId, String requestHex) {

        if (deviceId == null) {
            throw new IllegalArgumentException("设备ID必须为正整数");
        }
        if (requestHex == null || requestHex.trim().isEmpty()) {
            throw new IllegalArgumentException("请求数据不能为空");
        }

        try {
            // 1. 解析请求
            ModbusRequest request = parseModbusRequest(requestHex);

            // 2. 根据设备ID和从站地址获取变量数据
            List<LowerComputerVariable> variables = getDeviceVariables(deviceId, request.slaveAddress, request.functionCode);

            // 3. 生成响应数据
            byte[] responseData = generateModbusResponse(request, variables);

            // 4. 转换为十六进制字符串
            return bytesToHex(responseData);

        } catch (Exception e) {
            throw new RuntimeException("处理Modbus请求失败" + e.getMessage());
        }
    }

    /**
     * 处理Modbus回复数据并更新到数据库
     * @param requestHex 发送的Modbus指令（十六进制字符串）
     * @param responseHex 接收到的Modbus回复（十六进制字符串）
     * @return 更新的变量数量
     */
    public int processModbusResponse(Integer deviceId, String requestHex, String responseHex, String port) {
        try {
            // 1. 解析请求指令，获取设备信息和寄存器信息
            ModbusRequestInfo requestInfo = parseRequestForDeviceInfo(requestHex);

            // 2. 解析回复数据
            ModbusResponseData responseData = parseModbusResponse(responseHex, requestInfo);

            // 3. 根据请求信息找到对应的设备变量
            List<LowerComputerVariable> targetVariables = findCompleteVariablesInRange(deviceId, requestInfo, port);

            // 定义mqtt更新的容器
            HashMap<Integer, Object> MQTTMap = new HashMap<>();

            // 4. 提取数据并更新到数据库
            int updateCount = updateVariablesSequentially(targetVariables, responseData, requestInfo, MQTTMap);

            // 根据下位机id与更新的变量去mqtt上位机设备更新
            MqttUpdateToMqttScreen(deviceId, MQTTMap);

            return updateCount;

        } catch (Exception e) {
            throw new RuntimeException("处理Modbus回复失败: " + e.getMessage(), e);
        }
    }

    // 更新Mqtt屏幕根据下位机id与下位机的变量
    private void MqttUpdateToMqttScreen(Integer deviceId, Map<Integer, Object> MQTTMap){
        // 1. 下位机变量ID列表
        List<Integer> lowerVariableIds = new ArrayList<>(MQTTMap.keySet());

        if (lowerVariableIds.isEmpty()) {
            return;
        }

        // 2. 查询变量映射关系
        List<MqttScreenVariableMappingVariable> variableMappings = mqttScreenVariableMappingVariableMapper.selectList(
                new QueryWrapper<MqttScreenVariableMappingVariable>()
                        .eq("lower_computer_id", deviceId)
                        .in("lower_variable_id", lowerVariableIds)
        );

        if (variableMappings.isEmpty()) {
            return;
        }

        // 3. 获取去重的屏幕ID
        Set<Integer> screenIds = variableMappings.stream()
                .map(MqttScreenVariableMappingVariable::getScreenId)
                .collect(Collectors.toSet());

        // 4. 批量查询屏幕设备信息
        List<DeviceInfo> screenDevices = deviceInfoMapper.selectList(
                new QueryWrapper<DeviceInfo>().in("id", screenIds)
        );

        Map<Integer, DeviceInfo> screenDeviceMap = screenDevices.stream()
                .collect(Collectors.toMap(DeviceInfo::getId, device -> device));

        // 5. 按屏幕分组变量映射
        Map<Integer, List<MqttScreenVariableMappingVariable>> screenVariablesMap = variableMappings.stream()
                .collect(Collectors.groupingBy(MqttScreenVariableMappingVariable::getScreenId));

        // 6. 为每个屏幕准备MQTT数据并发送
        screenIds.forEach(screenId -> {
            DeviceInfo screenDevice = screenDeviceMap.get(screenId);
            if (screenDevice == null) return;

            // 获取该屏幕的所有变量映射
            List<MqttScreenVariableMappingVariable> screenVars = screenVariablesMap.get(screenId);
            if (screenVars == null || screenVars.isEmpty()) return;

            // 构建该屏幕的MQTT数据
            Map<String, Object> screenMqttData = buildScreenMqttData(screenVars, MQTTMap);

            // 发送到对应屏幕
            mqttMessageService.sendMessage(screenDevice.getHardwareAddress() + "/subcribe", JSONUtil.toJSON(screenMqttData));
        });
    }

    /**
     * 构建屏幕的MQTT数据
     */
    private Map<String, Object> buildScreenMqttData(List<MqttScreenVariableMappingVariable> screenVars,
                                                    Map<Integer, Object> mqttMap) {
        Map<String, Object> screenData = new HashMap<>();

        for (MqttScreenVariableMappingVariable mapping : screenVars) {
            // 从MQTTMap中获取对应的变量值
            Object value = mqttMap.get(mapping.getLowerVariableId());
            if (value != null) {
                // 使用MQTT变量名作为key
                screenData.put(mapping.getMqttVariableName(), value);
            }
        }

        return screenData;
    }



    /**
     * 查找请求范围内的完整变量 - 修正版（支持位类型）
     */
    private List<LowerComputerVariable> findCompleteVariablesInRange(Integer deviceId, ModbusRequestInfo requestInfo, String port) {
        QueryWrapper<LowerComputerVariable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId)
                .eq("slave_address", requestInfo.slaveAddress)
                .eq("register_type", getRegisterTypeByFunctionCode(requestInfo.functionCode))
                .eq("port", port)
                .orderByAsc("register_address");

        List<LowerComputerVariable> allVariables = variableMapper.selectList(queryWrapper);
        List<LowerComputerVariable> result = new ArrayList<>();

        boolean isBitType = isBitRegisterType(requestInfo.functionCode);
        int requestStart = requestInfo.startAddress;
        int requestEnd = requestStart + requestInfo.registerCount - 1;

        for (LowerComputerVariable variable : allVariables) {
            int varStart = variable.getRegisterAddress();
            int varCount;

            if (isBitType) {
                // 位类型：每个变量占用1个位
                varCount = 1;
            } else {
                // 寄存器类型：根据数据类型计算占用寄存器数量
                varCount = getRegisterCount(variable.getDataType());
            }

            int varEnd = varStart + varCount - 1;

            // 只添加在请求范围内的变量
            if (varStart >= requestStart && varStart <= requestEnd) {
                // 检查变量是否完全在请求范围内
                if (varEnd <= requestEnd) {
                    result.add(variable);
                } else {
                    System.err.println("警告: 变量 " + variable.getVariableName() + " 部分超出请求范围");
                }
            }
        }

        return result;
    }

    /**
     * 按顺序更新变量 - 完整修正版（支持所有类型）
     */
    private int updateVariablesSequentially(List<LowerComputerVariable> variables,
                                            ModbusResponseData responseData,
                                            ModbusRequestInfo requestInfo, Map<Integer, Object> MQTTMap) {
        int updateCount = 0;

        for (LowerComputerVariable variable : variables) {
            try {
                String newValue;

                if (isBitRegisterType(requestInfo.functionCode)) {
                    // 位类型处理（线圈、离散输入）
                    newValue = extractBitValue(responseData.rawData, variable, requestInfo);
                } else {
                    // 寄存器类型处理（保持寄存器、输入寄存器）
                    if ("bool".equals(variable.getDataType().toLowerCase()) &&
                            ("holding_register".equals(variable.getRegisterType()) ||
                                    "input_register".equals(variable.getRegisterType()))) {
                        // 保持寄存器或输入寄存器中的bool类型，需要按位提取
                        newValue = extractBitValueFromRegister(responseData.rawData, variable, requestInfo);
                    } else {
                        // 其他寄存器类型（int16, uint16, float32, int32等）
                        int variableOffset = variable.getRegisterAddress() - requestInfo.startAddress;
                        int byteOffset = variableOffset * 2; // 每个寄存器2字节
                        newValue = extractValueWithByteOrder(responseData.rawData, byteOffset, variable);
                    }
                }

                if (newValue != null && !newValue.equals(variable.getCurrentValue())) {
                    // 更新变量值
                    variable.setCurrentValue(newValue);
                    variableMapper.updateById(variable);
                    updateCount++;
                    System.out.println("更新变量: " + variable.getVariableName() + " = " + newValue);
                    MQTTMap.put(variable.getId(), newValue);
                }

            } catch (Exception e) {
                System.err.println("更新变量失败: " + variable.getVariableName() + " - " + e.getMessage());
            }
        }

        return updateCount;
    }

    /**
     * 提取位值 - 最终修正版
     */
    private String extractBitValue(byte[] rawData, LowerComputerVariable variable, ModbusRequestInfo requestInfo) {
        try {
            // 计算变量在回复数据中的位偏移
            int bitOffset = variable.getRegisterAddress() - requestInfo.startAddress;
            int bitPosition = variable.getBitPosition(); // 变量在字节中的位位置（0-7）

            // 计算字节偏移
            int byteIndex = bitOffset / 8;

            // 确保数据足够
            if (byteIndex >= rawData.length) {
                throw new RuntimeException("回复数据长度不足，需要字节索引: " + byteIndex + "，实际长度: " + rawData.length);
            }

            // 提取字节值
            byte targetByte = rawData[byteIndex];

            // 根据位位置提取位值
            boolean bitValue = ((targetByte >> bitPosition) & 0x01) == 1;

            return bitValue ? "1" : "0";

        } catch (Exception e) {
            throw new RuntimeException("提取位值失败 - 变量: " + variable.getVariableName() +
                    ", 地址: " + variable.getRegisterAddress() +
                    ", 位位置: " + variable.getBitPosition() +
                    " - " + e.getMessage(), e);
        }
    }

    /**
     * 判断是否为位寄存器类型
     */
    private boolean isBitRegisterType(String registerType) {
        return "coil".equals(registerType) || "discrete_input".equals(registerType);
    }

    /**
     * 根据功能码判断是否为位类型
     */
    private boolean isBitRegisterType(int functionCode) {
        return functionCode == 0x01 || functionCode == 0x02;
    }

    /**
     * 考虑字节序提取值 - 修复问题4
     */
    private String extractValueWithByteOrder(byte[] rawData, int byteOffset, LowerComputerVariable variable) {
        try {
            String dataType = variable.getDataType().toLowerCase();
            int registerCount = getRegisterCount(dataType);
            int byteCount = registerCount * 2;

            // 确保数据足够
            if (byteOffset + byteCount > rawData.length) {
                throw new RuntimeException("回复数据长度不足，需要 " + byteCount + " 字节，实际剩余 " + (rawData.length - byteOffset) + " 字节");
            }

            // 提取数据段
            byte[] valueBytes = Arrays.copyOfRange(rawData, byteOffset, byteOffset + byteCount);

            // 根据字节序处理数据
            String byteOrder = variable.getByteOrder() != null ? variable.getByteOrder().toLowerCase() : "big_endian";
            if ("little_endian".equals(byteOrder) && registerCount > 1) {
                valueBytes = swapByteOrder(valueBytes, registerCount);
            }

            ByteArrayInputStream bais = new ByteArrayInputStream(valueBytes);
            DataInputStream dis = new DataInputStream(bais);

            switch (dataType) {
                case "bool":
                    int boolValue = dis.readUnsignedByte();
                    return boolValue != 0 ? "1" : "0";

                case "int16":
                    short int16Value = dis.readShort();
                    return applyInverseScaling(String.valueOf(int16Value), variable.getScaleFactor());

                case "uint16":
                    int uint16Value = dis.readUnsignedShort();
                    return applyInverseScaling(String.valueOf(uint16Value), variable.getScaleFactor());

                case "float32":
                    float floatValue = dis.readFloat();
                    return applyInverseScaling(String.valueOf(floatValue), variable.getScaleFactor());

                case "int32":
                    int int32Value = dis.readInt();
                    return applyInverseScaling(String.valueOf(int32Value), variable.getScaleFactor());

                case "uint32":
                    long uint32Value = dis.readInt() & 0xFFFFFFFFL;
                    return applyInverseScaling(String.valueOf(uint32Value), variable.getScaleFactor());

                // 在 extractValueWithByteOrder 的 switch 语句中添加：
                case "int64":
                    long int64Value = dis.readLong();
                    return applyInverseScaling(String.valueOf(int64Value), variable.getScaleFactor());

                case "uint64":
                    // 注意：Java没有无符号long，需要特殊处理
                    long uint64Value = dis.readLong();
                    if (uint64Value < 0) {
                        BigInteger bigValue = new BigInteger(1, valueBytes);
                        return applyInverseScaling(bigValue.toString(), variable.getScaleFactor());
                    }
                    return applyInverseScaling(String.valueOf(uint64Value), variable.getScaleFactor());

                case "double":
                    double doubleValue = dis.readDouble();
                    return applyInverseScaling(String.valueOf(doubleValue), variable.getScaleFactor());

                default:
                    int defaultValue = dis.readUnsignedShort();
                    return String.valueOf(defaultValue);
            }

        } catch (IOException e) {
            throw new RuntimeException("解析回复数据失败", e);
        }
    }

    /**
     * 交换字节序 - 修复问题4
     */
    private byte[] swapByteOrder(byte[] data, int registerCount) {
        byte[] swapped = new byte[data.length];

        // 处理多寄存器字节序（字交换）
        if (registerCount > 1) {
            for (int i = 0; i < registerCount / 2; i++) {
                int base1 = i * 4;
                int base2 = base1 + 2;

                // 交换寄存器顺序
                swapped[base1] = data[base2];
                swapped[base1 + 1] = data[base2 + 1];
                swapped[base2] = data[base1];
                swapped[base2 + 1] = data[base1 + 1];
            }
        } else {
            // 单寄存器只交换字节
            for (int i = 0; i < registerCount; i++) {
                int base = i * 2;
                swapped[base] = data[base + 1];
                swapped[base + 1] = data[base];
            }
        }

        return swapped;
    }

    /**
     * 解析Modbus请求指令，提取设备信息
     */
    private ModbusRequestInfo parseRequestForDeviceInfo(String requestHex) {
        byte[] data = hexStringToBytes(requestHex);

        ModbusRequestInfo info = new ModbusRequestInfo();
        info.slaveAddress = data[0] & 0xFF;
        info.functionCode = data[1] & 0xFF;
        info.startAddress = ((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
        info.registerCount = ((data[4] & 0xFF) << 8) | (data[5] & 0xFF);
        info.requestHex = requestHex;

        return info;
    }

    /**
     * 解析Modbus回复数据
     */
    private ModbusResponseData parseModbusResponse(String responseHex, ModbusRequestInfo requestInfo) {
        byte[] data = hexStringToBytes(responseHex);

        ModbusResponseData responseData = new ModbusResponseData();
        responseData.slaveAddress = data[0] & 0xFF;
        responseData.functionCode = data[1] & 0xFF;
        responseData.dataLength = data[2] & 0xFF;

        // 提取数据部分（排除地址、功能码、长度和CRC）
        responseData.rawData = Arrays.copyOfRange(data, 3, data.length - 2);
        responseData.responseHex = responseHex;

        return responseData;
    }

    /**
     * 根据功能码获取寄存器类型
     */
    private String getRegisterTypeByFunctionCode(int functionCode) {
        switch (functionCode) {
            case 0x01: return "coil";
            case 0x02: return "discrete_input";
            case 0x03: return "holding_register";
            case 0x04: return "input_register";
            default: throw new RuntimeException("不支持的功能码: " + functionCode);
        }
    }


    /**
     * 从回复数据中提取变量值
     */
    private String extractValueFromResponse(byte[] rawData, int offset, LowerComputerVariable variable) {
        try {
            String dataType = variable.getDataType().toLowerCase();
            int registerCount = getRegisterCount(dataType);

            // 确保数据足够
            if (offset * 2 + registerCount * 2 > rawData.length) {
                throw new RuntimeException("回复数据长度不足");
            }

            ByteArrayInputStream bais = new ByteArrayInputStream(rawData, offset * 2, registerCount * 2);
            DataInputStream dis = new DataInputStream(bais);

            switch (dataType) {
                case "bool":
                    int boolValue = dis.readUnsignedByte();
                    return boolValue != 0 ? "1" : "0";

                case "int16":
                    short int16Value = dis.readShort();
                    return applyInverseScaling(String.valueOf(int16Value), variable.getScaleFactor());

                case "uint16":
                    int uint16Value = dis.readUnsignedShort();
                    return applyInverseScaling(String.valueOf(uint16Value), variable.getScaleFactor());

                case "float32":
                    float floatValue = dis.readFloat();
                    return applyInverseScaling(String.valueOf(floatValue), variable.getScaleFactor());

                case "int32":
                    int int32Value = dis.readInt();
                    return applyInverseScaling(String.valueOf(int32Value), variable.getScaleFactor());

                case "uint32":
                    long uint32Value = dis.readInt() & 0xFFFFFFFFL;
                    return applyInverseScaling(String.valueOf(uint32Value), variable.getScaleFactor());

                default:
                    int defaultValue = dis.readUnsignedShort();
                    return String.valueOf(defaultValue);
            }

        } catch (IOException e) {
            throw new RuntimeException("解析回复数据失败", e);
        }
    }

    /**
     * 应用反向缩放系数（将缩放后的值还原为原始值）
     */
    private String applyInverseScaling(String scaledValue, BigDecimal scalingFactor) {
        try {
            if (scaledValue == null) {
                return "0";
            }

            if (scalingFactor == null || scalingFactor.equals(BigDecimal.ONE)) {
                return scaledValue;
            }

            double value = Double.parseDouble(scaledValue);
            double originalValue = value / scalingFactor.doubleValue();

            // 根据数据类型格式化输出
            if (scaledValue.contains(".")) {
                return String.valueOf(originalValue);
            } else {
                return String.valueOf((long) originalValue); // 使用long避免溢出
            }

        } catch (NumberFormatException e) {
            return scaledValue != null ? scaledValue : "0";
        }
    }

    /**
     * Modbus请求信息内部类
     */
    private static class ModbusRequestInfo {
        int slaveAddress;
        int functionCode;
        int startAddress;
        int registerCount;
        String requestHex;
    }

    /**
     * Modbus回复数据内部类
     */
    private static class ModbusResponseData {
        int slaveAddress;
        int functionCode;
        int dataLength;
        byte[] rawData;
        String responseHex;
    }

    /**
     * 解析Modbus请求
     */
    private ModbusRequest parseModbusRequest(String requestHex) {
        byte[] data = hexStringToBytes(requestHex);

        ModbusRequest request = new ModbusRequest();
        request.slaveAddress = data[0] & 0xFF;
        request.functionCode = data[1] & 0xFF;
        request.startAddress = ((data[2] & 0xFF) << 8) | (data[3] & 0xFF);
        request.registerCount = ((data[4] & 0xFF) << 8) | (data[5] & 0xFF);

        return request;
    }

    /**
     * 获取设备变量数据
     */
    private List<LowerComputerVariable> getDeviceVariables(Integer deviceId, int slaveAddress, int functionCode) {
        QueryWrapper<LowerComputerVariable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("device_id", deviceId)
                .eq("slave_address", slaveAddress)
                .eq("register_type", getRegisterTypeByFunctionCode(functionCode))
                .orderByAsc("register_address");
        return variableMapper.selectList(queryWrapper);
    }

    /**
     * 生成Modbus响应
     */
    private byte[] generateModbusResponse(ModbusRequest request, List<LowerComputerVariable> variables) {
        try {
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            DataOutputStream dataStream = new DataOutputStream(byteStream);

            // 设备地址
            dataStream.writeByte(request.slaveAddress);

            // 功能码
            dataStream.writeByte(request.functionCode);

            // 数据字节数
            int dataLength = calculateResponseDataLength(request, variables);
            dataStream.writeByte(dataLength);

            // 响应数据
            byte[] responseData = generateResponseData(request, variables);
            dataStream.write(responseData);

            dataStream.flush();
            byte[] responseWithoutCRC = byteStream.toByteArray();

            // 计算CRC
            int crc = calculateCRC16(responseWithoutCRC);
            dataStream.writeByte(crc & 0xFF);
            dataStream.writeByte((crc >> 8) & 0xFF);

            dataStream.flush();
            return byteStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException("生成响应失败", e);
        }
    }

    /**
     * 计算响应数据长度
     */
    private int calculateResponseDataLength(ModbusRequest request, List<LowerComputerVariable> variables) {
        switch (request.functionCode) {
            case 0x01: // 读线圈
            case 0x02: // 读离散输入
                // 每个字节包含8个位
                return (request.registerCount + 7) / 8;

            case 0x03: // 读保持寄存器
            case 0x04: // 读输入寄存器
                // 每个寄存器2字节
                return request.registerCount * 2;

            default:
                return 0;
        }
    }

    /**
     * 生成响应数据
     */
    private byte[] generateResponseData(ModbusRequest request, List<LowerComputerVariable> variables) {
        try {
            ByteArrayOutputStream dataStream = new ByteArrayOutputStream();

            switch (request.functionCode) {
                case 0x01: // 读线圈
                case 0x02: // 读离散输入
                    generateBitResponse(dataStream, request, variables);
                    break;

                case 0x03: // 读保持寄存器
                case 0x04: // 读输入寄存器
                    generateRegisterResponse(dataStream, request, variables);
                    break;
            }

            return dataStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException("生成响应数据失败", e);
        }
    }

    /**
     * 生成位响应（线圈/离散输入）
     */
    private void generateBitResponse(ByteArrayOutputStream dataStream,
                                     ModbusRequest request,
                                     List<LowerComputerVariable> variables) throws IOException {
        int byteCount = (request.registerCount + 7) / 8;
        byte[] responseBytes = new byte[byteCount];

        for (int i = 0; i < request.registerCount; i++) {
            int currentAddress = request.startAddress + i;
            Boolean value = getVariableValue(variables, currentAddress, "bool");

            if (value != null && value) {
                int byteIndex = i / 8;
                int bitIndex = i % 8;
                responseBytes[byteIndex] |= (1 << bitIndex);
            }
        }

        dataStream.write(responseBytes);
    }

    private void generateRegisterResponse(ByteArrayOutputStream dataStream,
                                          ModbusRequest request,
                                          List<LowerComputerVariable> variables) throws IOException {
        DataOutputStream output = new DataOutputStream(dataStream);

        // 为请求范围内的每个地址生成数据
        for (int i = 0; i < request.registerCount; i++) {
            int currentAddress = request.startAddress + i;

            // 查找该地址的主要变量（非bool类型优先）
            LowerComputerVariable primaryVariable = findPrimaryVariableByAddress(variables, currentAddress);

            if (primaryVariable != null) {
                // 处理主要变量（考虑多寄存器数据类型）
                int registerCount = getRegisterCount(primaryVariable.getDataType());
                byte[] registerData = convertValueToRegisters(primaryVariable, registerCount);

                // 计算在当前寄存器中的偏移
                int variableOffset = currentAddress - primaryVariable.getRegisterAddress();
                int byteOffset = variableOffset * 2;

                // 计算需要写入的数据量
                int remainingInVariable = registerCount - variableOffset;
                int remainingInRequest = request.registerCount - i;
                int writeCount = Math.min(remainingInVariable, remainingInRequest);

                // 写入数据
                output.write(registerData, byteOffset, writeCount * 2);

                i += (writeCount - 1); // 跳过已处理的寄存器
            } else {
                // 检查是否有bool类型的变量需要合并
                List<LowerComputerVariable> boolVariables = findBoolVariablesByAddress(variables, currentAddress);
                if (!boolVariables.isEmpty()) {
                    short mergedValue = mergeBoolVariables(boolVariables);
                    output.writeShort(mergedValue);
                } else {
                    // 没有变量，填充0
                    output.writeShort(0);
                }
            }
        }
    }

    /**
     * 查找指定地址的主要变量（非bool类型优先）
     */
    private LowerComputerVariable findPrimaryVariableByAddress(List<LowerComputerVariable> variables, int address) {
        // 先找非bool类型的变量
        for (LowerComputerVariable variable : variables) {
            if (!"bool".equals(variable.getDataType().toLowerCase())) {
                int varStart = variable.getRegisterAddress();
                int varCount = getRegisterCount(variable.getDataType());
                int varEnd = varStart + varCount - 1;

                if (address >= varStart && address <= varEnd) {
                    return variable;
                }
            }
        }
        return null;
    }

    /**
     * 查找指定地址的bool类型变量
     */
    private List<LowerComputerVariable> findBoolVariablesByAddress(List<LowerComputerVariable> variables, int address) {
        List<LowerComputerVariable> result = new ArrayList<>();
        for (LowerComputerVariable variable : variables) {
            if ("bool".equals(variable.getDataType().toLowerCase())) {
                int varStart = variable.getRegisterAddress();
                int varCount = getRegisterCount(variable.getDataType());
                int varEnd = varStart + varCount - 1;

                if (address >= varStart && address <= varEnd) {
                    result.add(variable);
                }
            }
        }
        return result;
    }

    /**
     * 合并bool类型变量
     */
    private short mergeBoolVariables(List<LowerComputerVariable> boolVariables) {
        int mergedValue = 0;
        for (LowerComputerVariable variable : boolVariables) {
            String currentValue = variable.getCurrentValue();
            if (currentValue != null) {
                boolean boolValue = "1".equals(currentValue) || "true".equalsIgnoreCase(currentValue);
                if (boolValue) {
                    int bitPosition = variable.getBitPosition();
                    mergedValue |= (1 << bitPosition);
                }
            }
        }
        return (short) mergedValue;
    }

    /**
     * 查找指定地址的所有变量
     */
    private List<LowerComputerVariable> findAllVariablesByAddress(List<LowerComputerVariable> variables, int address) {
        List<LowerComputerVariable> result = new ArrayList<>();
        for (LowerComputerVariable variable : variables) {
            int varStart = variable.getRegisterAddress();
            int varCount = getRegisterCount(variable.getDataType());
            int varEnd = varStart + varCount - 1;

            // 检查地址是否在变量范围内
            if (address >= varStart && address <= varEnd) {
                result.add(variable);
            }
        }
        return result;
    }

    /**
     * 合并同一地址的所有变量值（支持保持寄存器中的bool类型）
     */
    private short mergeRegisterVariablesAtAddress(List<LowerComputerVariable> variables, int address) {
        int mergedValue = 0;

        // 先处理非bool类型的变量
        for (LowerComputerVariable variable : variables) {
            String dataType = variable.getDataType().toLowerCase();

            if (!"bool".equals(dataType)) {
                // 非bool类型，直接取值
                try {
                    String currentValue = variable.getCurrentValue();
                    if (currentValue != null) {
                        double scaledValue = applyScalingFactor(currentValue, variable.getScaleFactor());

                        if ("float32".equals(dataType)) {
                            // float32特殊处理
                            float floatValue = (float) scaledValue;
                            int intBits = Float.floatToIntBits(floatValue);
                            return (short) (intBits >> 16); // 返回高16位或低16位，根据地址偏移
                        } else if ("int32".equals(dataType) || "uint32".equals(dataType)) {
                            int intValue = (int) scaledValue;
                            return (short) (intValue >> 16); // 返回高16位或低16位
                        } else {
                            // int16, uint16等
                            return (short) scaledValue;
                        }
                    }
                } catch (Exception e) {
                    // 忽略错误
                }
                break; // 非bool类型通常只有一个，找到后就退出
            }
        }

        // 再处理bool类型的变量（位合并）
        for (LowerComputerVariable variable : variables) {
            String dataType = variable.getDataType().toLowerCase();

            if ("bool".equals(dataType)) {
                String currentValue = variable.getCurrentValue();
                if (currentValue != null) {
                    boolean boolValue = "1".equals(currentValue) || "true".equalsIgnoreCase(currentValue);
                    if (boolValue) {
                        int bitPosition = variable.getBitPosition();
                        mergedValue |= (1 << bitPosition);
                    }
                }
            }
        }

        return (short) mergedValue;
    }

    /**
     * 从寄存器数据中提取位值（用于保持寄存器中的bool类型）
     */
    private String extractBitValueFromRegister(byte[] rawData, LowerComputerVariable variable, ModbusRequestInfo requestInfo) {
        try {
            // 计算变量在回复数据中的寄存器偏移
            int registerOffset = variable.getRegisterAddress() - requestInfo.startAddress;
            int bitPosition = variable.getBitPosition();

            // 计算字节偏移（每个寄存器2字节）
            int byteOffset = registerOffset * 2;

            // 确保数据足够
            if (byteOffset + 2 > rawData.length) {
                throw new RuntimeException("回复数据长度不足");
            }

            // 提取寄存器值
            int registerValue = ((rawData[byteOffset] & 0xFF) << 8) | (rawData[byteOffset + 1] & 0xFF);

            // 根据位位置提取位值
            boolean bitValue = ((registerValue >> bitPosition) & 0x01) == 1;

            return bitValue ? "1" : "0";

        } catch (Exception e) {
            throw new RuntimeException("从寄存器提取位值失败 - 变量: " + variable.getVariableName() +
                    ", 地址: " + variable.getRegisterAddress() +
                    ", 位位置: " + variable.getBitPosition() +
                    " - " + e.getMessage(), e);
        }
    }

    /**
     * 根据变量值转换为寄存器数组 - 支持部分写入
     */
    private byte[] convertValueToRegisters(LowerComputerVariable variable, int registerCount) {
        try {
            String currentValue = variable.getCurrentValue();
            if (currentValue == null) {
                return new byte[registerCount * 2];
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(baos);

            String dataType = variable.getDataType().toLowerCase();
            double scaledValue = applyScalingFactor(currentValue, variable.getScaleFactor());

            switch (dataType) {
                case "bool":
                    boolean boolValue = Boolean.parseBoolean(currentValue);
                    dos.writeShort(boolValue ? 1 : 0);
                    break;

                case "int16":
                    short int16Value = (short) scaledValue;
                    dos.writeShort(int16Value);
                    break;

                case "uint16":
                    int uint16Value = Math.max(0, Math.min(65535, (int) scaledValue));
                    dos.writeShort(uint16Value);
                    break;

                case "float32":
                    // 如果只需要部分寄存器，不能写入完整的float32
                    if (registerCount >= 2) {
                        float floatValue = (float) scaledValue;
                        dos.writeFloat(floatValue);
                    } else {
                        // 只写入前2个字节
                        float floatValue = (float) scaledValue;
                        int intBits = Float.floatToIntBits(floatValue);
                        dos.writeShort(intBits >> 16); // 高16位
                    }
                    break;

                case "int32":
                case "uint32":
                    // 如果只需要部分寄存器，不能写入完整的int32
                    if (registerCount >= 2) {
                        int int32Value = (int) scaledValue;
                        dos.writeInt(int32Value);
                    } else {
                        // 只写入前2个字节
                        int int32Value = (int) scaledValue;
                        dos.writeShort(int32Value >> 16); // 高16位
                    }
                    break;

                default:
                    int defaultValue = (int) scaledValue;
                    dos.writeShort(defaultValue);
            }

            dos.flush();
            return baos.toByteArray();

        } catch (Exception e) {
            System.err.println("转换变量值失败: " + variable.getVariableName());
            return new byte[registerCount * 2];
        }
    }

    /**
     * 根据is_readonly字段转换为boolean
     */
    private boolean convertToBoolean(String value, String isReadonly) {
        if (isReadonly != null) {
            // 根据你的业务逻辑转换只读字段
            switch (isReadonly.toLowerCase()) {
                case "1":
                case "true":
                case "yes":
                case "readonly":
                    return true;
                case "0":
                case "false":
                case "no":
                case "readwrite":
                    return false;
            }
        }

        // 默认按值本身转换
        return Boolean.parseBoolean(value);
    }

    /**
     * 应用缩放系数到原始值
     */
    private double applyScalingFactor(String rawValue, BigDecimal scalingFactor) {
        try {
            if (scalingFactor == null || scalingFactor.equals(BigDecimal.ONE)) {
                // 没有缩放系数或为1，直接返回原值
                return Double.parseDouble(rawValue);
            }

            double value = Double.parseDouble(rawValue);
            return value * scalingFactor.doubleValue();

        } catch (NumberFormatException e) {
            System.err.println("缩放系数应用失败，原始值: " + rawValue);
            return 0.0;
        }
    }


    /**
     * 获取变量值
     */
    /**
     * 获取变量值 - 修正版（支持多种布尔值格式）
     */
    private Boolean getVariableValue(List<LowerComputerVariable> variables, int address, String expectedType) {
        LowerComputerVariable variable = findVariableByAddress(variables, address);
        if (variable != null && variable.getCurrentValue() != null) {
            String value = variable.getCurrentValue().trim().toLowerCase();

            // 支持多种布尔值格式
            if ("1".equals(value) || "true".equals(value) || "on".equals(value)) {
                return true;
            } else if ("0".equals(value) || "false".equals(value) || "off".equals(value)) {
                return false;
            }

            // 尝试解析为数字
            try {
                int intValue = Integer.parseInt(value);
                return intValue != 0;
            } catch (NumberFormatException e) {
                return false;
            }
        }
        return false;
    }

    /**
     * 根据地址查找变量 - 严格匹配版
     */
    private LowerComputerVariable findVariableByAddress(List<LowerComputerVariable> variables, int address) {
        for (LowerComputerVariable variable : variables) {
            int varStart = variable.getRegisterAddress();
            int varCount = getRegisterCount(variable.getDataType());
            int varEnd = varStart + varCount - 1;

            // 检查地址是否在变量范围内
            if (address >= varStart && address <= varEnd) {
                // 查询的地址名
//                System.out.println(variable);
                return variable;
            }
        }
        return null;
    }


    /**
     * 十六进制字符串转字节数组
     */
    private byte[] hexStringToBytes(String hex) {
        int len = hex.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                    + Character.digit(hex.charAt(i+1), 16));
        }
        return data;
    }

    /**
     * Modbus请求内部类
     */
    private static class ModbusRequest {
        int slaveAddress;
        int functionCode;
        int startAddress;
        int registerCount;
    }



    /**
     * 按从站地址和寄存器类型分组变量
     */
    private Map<String, List<LowerComputerVariable>> groupVariables(List<LowerComputerVariable> variables) {
        Map<String, List<LowerComputerVariable>> groups = new HashMap<>();

        for (LowerComputerVariable variable : variables) {
            String key = variable.getSlaveAddress() + "_" + variable.getRegisterType();
            groups.computeIfAbsent(key, k -> new ArrayList<>()).add(variable);
        }

        return groups;
    }

    /**
     * 合并连续的地址 - 最终修正版
     */
    private List<AddressRange> mergeContinuousAddresses(List<LowerComputerVariable> variables) {
        List<AddressRange> ranges = new ArrayList<>();
        if (variables.isEmpty()) return ranges;

        // 按寄存器地址排序
        variables.sort((v1, v2) -> v1.getRegisterAddress().compareTo(v2.getRegisterAddress()));

        LowerComputerVariable first = variables.get(0);
        boolean isBitType = isBitRegisterType(first.getRegisterType());

        int slaveAddress = first.getSlaveAddress();
        String registerType = first.getRegisterType();

        if (isBitType) {
            // 位类型：按字节合并，考虑位位置
            ranges = mergeBitAddresses(variables, slaveAddress, registerType);
        } else {
            // 寄存器类型：按原逻辑
            ranges = mergeRegisterAddresses(variables, slaveAddress, registerType);
        }

        return ranges;
    }

    /**
     * 合并位地址 - 新增方法
     */
    /**
     * 合并位地址 - 修正版（添加去重逻辑）
     */
    private List<AddressRange> mergeBitAddresses(List<LowerComputerVariable> variables, int slaveAddress, String registerType) {
        List<AddressRange> ranges = new ArrayList<>();

        // 1. 先按寄存器地址去重
        Set<Integer> uniqueAddresses = new HashSet<>();
        for (LowerComputerVariable variable : variables) {
            uniqueAddresses.add(variable.getRegisterAddress());
        }

        // 2. 排序去重后的地址
        List<Integer> sortedAddresses = new ArrayList<>(uniqueAddresses);
        Collections.sort(sortedAddresses);

        if (sortedAddresses.isEmpty()) return ranges;

        // 3. 合并连续地址
        int currentStart = sortedAddresses.get(0);
        int currentEnd = currentStart;

        for (int i = 1; i < sortedAddresses.size(); i++) {
            int currentAddr = sortedAddresses.get(i);

            // 检查地址是否连续
            if (currentAddr == currentEnd + 1) {
                currentEnd = currentAddr;
            } else {
                // 不连续，保存当前范围
                int bitCount = currentEnd - currentStart + 1;
                ranges.add(new AddressRange(slaveAddress, registerType, currentStart, bitCount, true));

                currentStart = currentAddr;
                currentEnd = currentAddr;
            }
        }

        // 添加最后一个范围
        int bitCount = currentEnd - currentStart + 1;
        ranges.add(new AddressRange(slaveAddress, registerType, currentStart, bitCount, true));

        return ranges;
    }

    /**
     * 合并寄存器地址 - 新增方法
     */
    /**
     * 合并寄存器地址 - 修正版（添加去重逻辑）
     */
    private List<AddressRange> mergeRegisterAddresses(List<LowerComputerVariable> variables, int slaveAddress, String registerType) {
        List<AddressRange> ranges = new ArrayList<>();

        // 1. 先按寄存器地址去重（相同地址只取第一个变量）
        Map<Integer, LowerComputerVariable> uniqueVariables = new HashMap<>();
        for (LowerComputerVariable variable : variables) {
            uniqueVariables.putIfAbsent(variable.getRegisterAddress(), variable);
        }

        // 2. 获取去重后的变量列表并排序
        List<LowerComputerVariable> uniqueVars = new ArrayList<>(uniqueVariables.values());
        uniqueVars.sort((v1, v2) -> v1.getRegisterAddress().compareTo(v2.getRegisterAddress()));

        if (uniqueVars.isEmpty()) return ranges;

        // 3. 合并连续地址
        LowerComputerVariable firstVar = uniqueVars.get(0);
        int start = firstVar.getRegisterAddress();
        int end = start + getRegisterCount(firstVar.getDataType()) - 1;

        for (int i = 1; i < uniqueVars.size(); i++) {
            LowerComputerVariable current = uniqueVars.get(i);
            int currentRegisterCount = getRegisterCount(current.getDataType());
            int currentEnd = current.getRegisterAddress() + currentRegisterCount - 1;

            // 检查是否连续
            if (current.getRegisterAddress() == end + 1) {
                end = currentEnd;
            } else {
                // 不连续，保存当前区间
                ranges.add(new AddressRange(slaveAddress, registerType, start, end - start + 1, false));

                // 开始新的区间
                start = current.getRegisterAddress();
                end = currentEnd;
            }
        }

        // 添加最后一个区间
        ranges.add(new AddressRange(slaveAddress, registerType, start, end - start + 1, false));

        return ranges;
    }

    /**
     * 根据数据类型获取占用的寄存器数量
     */
    private int getRegisterCount(String dataType) {
        switch (dataType.toLowerCase()) {
            case "int16":
            case "uint16":
            case "bool":
                return 1;
            case "int32":
            case "uint32":
            case "float32":
                return 2;
            case "int64":
            case "uint64":
            case "double":
                return 4;
            default:
                return 1;
        }
    }

    /**
     * 生成Modbus指令字符串 - 最终修正版
     */
    private String generateModbusCommandString(AddressRange range) {
        try {
            // 手动构建Modbus RTU指令字节数组
            byte[] messageData = buildModbusRTUCommand(
                    range.slaveAddress,
                    range.registerType,
                    range.startAddress,
                    range.count  // 对于位类型是位数，对于寄存器类型是寄存器数量
            );

            return bytesToHex(messageData);

        } catch (Exception e) {
            System.err.println("生成Modbus指令失败 - 从站: " + range.slaveAddress +
                    ", 类型: " + range.registerType +
                    ", 地址: " + range.startAddress +
                    ", 数量: " + range.count +
                    " - " + e.getMessage());
            return null;
        }
    }

    /**
     * 手动构建Modbus RTU指令
     */
    private byte[] buildModbusRTUCommand(int slaveAddress, String registerType, int startAddress, int registerCount) {
        try {
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            DataOutputStream dataStream = new DataOutputStream(byteStream);

            // 1. 设备地址 (1字节)
            dataStream.writeByte(slaveAddress);

            // 2. 功能码 (1字节)
            byte functionCode = getFunctionCode(registerType);
            dataStream.writeByte(functionCode);

            // 3. 起始地址 (2字节，大端序)
            dataStream.writeShort(startAddress);

            // 4. 寄存器数量 (2字节，大端序)
            dataStream.writeShort(registerCount);

            dataStream.flush();

            // 5. 获取数据部分（不包含CRC）
            byte[] dataWithoutCRC = byteStream.toByteArray();

            // 6. 计算CRC16校验码
            int crc = calculateCRC16(dataWithoutCRC);

            // 7. 添加CRC校验码（小端序）
            dataStream.writeByte(crc & 0xFF);        // 低字节
            dataStream.writeByte((crc >> 8) & 0xFF); // 高字节

            dataStream.flush();
            return byteStream.toByteArray();

        } catch (IOException e) {
            throw new RuntimeException("构建Modbus指令失败", e);
        }
    }

    /**
     *  根据寄存器类型获取功能码
     */
    private byte getFunctionCode(String registerType) {
        switch (registerType.toLowerCase()) {
            case "coil":
                return 0x01; // 读线圈
            case "discrete_input":
                return 0x02;
            case "input_register":
                return 0x04; // 读输入寄存器
            case "holding_register":
                return 0x03; // 读保持寄存器
            default:
                return 0x03; // 默认读保持寄存器
        }
    }

    /**
     *  计算Modbus CRC16校验码
     */
    private int calculateCRC16(byte[] data) {
        int crc = 0xFFFF;

        if (data == null || data.length == 0) {
            return crc;
        }

        for (byte b : data) {
            crc ^= (b & 0xFF);

            for (int i = 0; i < 8; i++) {
                boolean carry = (crc & 0x0001) != 0;
                crc = crc >> 1;
                if (carry) {
                    crc ^= 0xA001;
                }
            }
        }

        return crc;
    }

    /**
     * 字节数组转十六进制字符串
     */
    private String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xFF & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString().toUpperCase();
    }

    /**
     * 地址区间内部类 - 重构版
     */
    private static class AddressRange {
        int slaveAddress;
        String registerType;
        int startAddress;
        int count; // 对于位类型是位数，对于寄存器类型是寄存器数量
        boolean isBitType;

        public AddressRange(int slaveAddress, String registerType, int startAddress, int count, boolean isBitType) {
            this.slaveAddress = slaveAddress;
            this.registerType = registerType;
            this.startAddress = startAddress;
            this.count = count;
            this.isBitType = isBitType;
        }
    }
}